<template>
  <div class="table-page-search-wrapper" style="padding: 0 20px">
    <a-form :model="dataObj" layout="vertical">
      <a-row :gutter="[8, 0]">
        <span
          v-if="['noCodeAdd', 'noCodeEdit'].includes(dataObj.mode)"
          class="custom-add-btn"
        >
          <a-radio-group
            v-model="dataObj.basicData.appType"
            @change="noCodeSelectChange"
          >
            <a-radio value="task">任务组件</a-radio>
            <a-radio value="api">api组件</a-radio>
            <a-radio value="sdk">sdk插件组件</a-radio>
          </a-radio-group>
        </span>
        <a-col
          :span="
            ['add', 'edit'].includes(dataObj.mode)
              ? index < buttonLength
                ? 12
                : 24
              : 24
          "
          v-for="(item, index) in dataObj.buttonData"
          :key="`${item.buttonEventAddDTO.eventType}_${index}`"
        >
          <a-form-item
            v-if="
              (['noCodeAdd', 'noCodeEdit'].includes(dataObj.mode) &&
                !labelNames.includes(item.buttonEventAddDTO.eventType)) ||
              ['add', 'edit'].includes(dataObj.mode)
            "
          >
            <template
              v-if="
                labelNames.includes(item.buttonEventAddDTO.eventType) &&
                index < buttonLength
              "
            >
              <span v-if="['add', 'edit'].includes(dataObj.mode)">
                <a-checkbox
                  v-if="index === 0"
                  :default-checked="true"
                  :disabled="true"
                  >查询</a-checkbox
                >
                <a-checkbox v-else v-model="item.checked">按钮名：</a-checkbox>
                <a-input
                  v-model="item.tableButtonAddDTO.buttonName"
                  placeholder="请输入按钮名"
                  :disabled="true"
                  class="custom-space custom-select"
                ></a-input>
                <a-select
                  style="width: 12%"
                  :default-value="`${item.tableButtonAddDTO.defaultFlag ? '0' : '1'}`"
                  @change="onChangeDefaultFlag($event, item)"
                >
                  <a-option
                    value="0"
                    v-if="item.buttonEventAddDTO.eventType !== 'details'"
                    >默认</a-option
                  >
                  <a-option
                    value="1"
                    v-if="
                      item.tableButtonAddDTO.buttonName !== '删除' &&
                      item.buttonEventAddDTO.eventType !== 'import' &&
                      item.buttonEventAddDTO.eventType !== 'export'
                    "
                    >自定义</a-option
                  >
                </a-select>
                <a-select
                  style="width: 15%"
                  class="custom-space"
                  placeholder="请选择需要图标"
                  v-model="item.tableButtonAddDTO.buttonIcon"
                >
                  <a-option
                    v-for="nameObj in buttonIconList"
                    :key="nameObj.value"
                    :value="nameObj.value"
                    >{{ nameObj.name }}</a-option
                  >
                </a-select>
                <a-select
                  class="custom-select custom-space"
                  v-if="item.buttonEventAddDTO.eventType === 'details'"
                  v-model="item.columnNum"
                >
                  <a-option :value="1">1列</a-option>
                  <a-option :value="2">2列</a-option>
                  <a-option :value="3">3列</a-option>
                  <a-option :value="4">4列</a-option>
                </a-select>

                <span v-if="item.buttonEventAddDTO.eventType === 'details'">
                  <a-select
                    multiple
                    style="width: 25%"
                    class="custom-select custom-space"
                    placeholder="请选择需要显示的字段"
                    v-model="item.displayFields"
                  >
                    <a-option
                      v-for="nameObj in allNameList"
                      :key="nameObj.value"
                      :value="nameObj.value"
                      >{{ nameObj.label }}</a-option
                    >
                  </a-select>
                </span>
                <span v-else>
                  <a-select
                    multiple
                    style="width: 30%"
                    class="custom-select custom-space"
                    placeholder="请选择需要显示的字段"
                    v-if="!item.tableButtonAddDTO.defaultFlag"
                    v-model="item.displayFields"
                  >
                    <a-option
                      v-for="nameObj in nameList"
                      :key="nameObj.value"
                      :value="nameObj.value"
                      >{{ nameObj.label }}</a-option
                    >
                  </a-select>
                  <!-- 禁用字段 -->
                  <a-select
                    multiple
                    style="width: 30%"
                    class="custom-select custom-space"
                    placeholder="请选择需要禁用的字段"
                    v-if="
                      !item.tableButtonAddDTO.defaultFlag &&
                      !['query', 'details'].includes(
                        item.buttonEventAddDTO.eventType
                      )
                    "
                    v-model="item.disabledFields"
                  >
                    <a-option
                      v-for="nameObj in nameList"
                      :key="nameObj.value"
                      :value="nameObj.value"
                      >{{ nameObj.label }}</a-option
                    >
                  </a-select>
                </span>
              </span>
            </template>
            <template v-else>
              <span v-if="['add', 'edit'].includes(dataObj.mode)">
                <span>自定义按钮名： </span>
                <a-input
                  v-model="item.tableButtonAddDTO.buttonName"
                  placeholder="请输入自定义按钮名"
                  class="custom-select custom-space"
                ></a-input>
                <a-select
                  class="custom-select custom-space"
                  placeholder="请选择需要图标"
                  v-model="item.tableButtonAddDTO.buttonIcon"
                >
                  <a-option
                    v-for="nameObj in buttonIconList"
                    :key="nameObj.value"
                    :value="nameObj.value"
                    >{{ nameObj.name }}</a-option
                  >
                </a-select>
                <a-select
                  class="custom-select custom-space"
                  v-model="item.buttonEventAddDTO.eventType"
                  placeholder="请选择"
                  @change="customChange($event, item)"
                >
                  <a-option value="plug">插件</a-option>
                  <!-- <a-option value="add">新增</a-option>-->
                  <a-option value="update">编辑</a-option>
                  <a-option value="details">查看</a-option>
                  <a-option value="flow">流程</a-option>
                  <a-option value="chart">图表</a-option>
                  <a-option value="report">报表</a-option>
                  <a-option value="batchUp">批量修改</a-option>
                  <a-option value="batchDel">批量删除</a-option>
                </a-select>
                <a-select
                  class="custom-select custom-space"
                  allow-clear
                  v-model="item.tableButtonAddDTO.buttonType"
                  placeholder="请选择按钮位置"
                >
                  <a-option
                    v-if="
                      !['details', 'update'].includes(
                        item.buttonEventAddDTO.eventType
                      )
                    "
                    value="top"
                    >全局</a-option
                  >
                  <a-option
                    value="data"
                    v-if="
                      !['report', 'chart', 'batchUp'].includes(
                        item.buttonEventAddDTO.eventType
                      )
                    "
                    >列表</a-option
                  >
                  <a-option
                    value="modalTop"
                    v-if="['flow'].includes(item.buttonEventAddDTO.eventType)"
                    >全局（录入多条）</a-option
                  >
                  <a-option
                    value="dataTop"
                    v-if="['flow'].includes(item.buttonEventAddDTO.eventType)"
                    >全局（录入单条）</a-option
                  >
                </a-select>
                <a-select
                  class="custom-select custom-space"
                  v-if="item.buttonEventAddDTO.eventType === 'details'"
                  v-model="item.columnNum"
                >
                  <a-option :value="1">1列</a-option>
                  <a-option :value="2">2列</a-option>
                  <a-option :value="3">3列</a-option>
                  <a-option :value="4">4列</a-option>
                </a-select>
                <a-select
                  multiple
                  style="width: 18%"
                  class="custom-space"
                  placeholder="请选择需要显示的字段"
                  v-if="
                    ['details', 'update', 'batchUp'].includes(
                      item.buttonEventAddDTO.eventType
                    )
                  "
                  v-model="item.displayFields"
                >
                  <a-option
                    v-for="nameObj in nameList"
                    :key="nameObj.value"
                    :value="nameObj.value"
                    >{{ nameObj.label }}</a-option
                  >
                </a-select>

                <!-- 禁用字段 -->
                <a-select
                  multiple
                  style="width: 18%"
                  class="custom-select custom-space"
                  placeholder="请选择需要禁用的字段"
                  v-if="
                    !item.tableButtonAddDTO.defaultFlag &&
                    ![
                      'query',
                      'details',
                      'flow',
                      'plug',
                      'chart',
                      'report',
                    ].includes(item.buttonEventAddDTO.eventType)
                  "
                  v-model="item.disabledFields"
                >
                  <a-option
                    v-for="nameObj in nameList"
                    :key="nameObj.value"
                    :value="nameObj.value"
                    >{{ nameObj.label }}</a-option
                  >
                </a-select>
              </span>
              <span
                v-if="
                  ['add', 'edit'].includes(dataObj.mode) ||
                  (['noCodeAdd', 'noCodeEdit'].includes(dataObj.mode) &&
                    dataObj.basicData.appType !== 'task')
                "
              >
                <!--    请选择数据源  -->
                <a-select
                  class="custom-select custom-space"
                  allow-clear
                  v-model="item.buttonEventAddDTO.foreignId"
                  v-if="item.buttonEventAddDTO.eventType === 'report'"
                  allow-search
                  placeholder="请选择数据源"
                  :filter-option="filterOption"
                >
                  <a-option
                    :value="val.dataId"
                    v-for="val in dataSourceList"
                    :key="val.dataId"
                  >
                    {{ val.dataName }}
                  </a-option>
                </a-select>
                <a-select
                  class="custom-select custom-space"
                  allow-clear
                  v-model="item.buttonEventAddDTO.foreignId"
                  v-if="item.buttonEventAddDTO.eventType === 'plug'"
                  allow-search
                  placeholder="请选择插件"
                  :filter-option="filterOption"
                  @change="secondLevChange($event, item, index)"
                >
                  <!--  :disabled="isDisabled.includes(val.plugId)" 插件禁止重复选择的   -->
                  <a-option
                    :value="val.plugId"
                    v-for="val in pluginfoList"
                    :key="val.plugId"
                  >
                    {{ val.plugName }}
                  </a-option>
                </a-select>
                <!-- 选择流程 -->
                <span v-if="item.buttonEventAddDTO.eventType === 'flow'">
                  <a-select
                    class="custom-select custom-space"
                    @search="(input) => queryFlowList(input)"
                    placeholder="请选择流程"
                    allow-search
                    allow-clear
                    :filter-option="false"
                    v-model="item.buttonEventAddDTO.foreignId"
                  >
                    <a-option
                      v-for="flow in flowList"
                      :key="flow.modelId"
                      :value="flow.modelId"
                      >{{ flow.modelName }}</a-option
                    >
                  </a-select>
                </span>
                <a-button
                  type="primary"
                  v-if="
                    item.buttonEventAddDTO.foreignId &&
                    ['plug', 'flow'].includes(item.buttonEventAddDTO.eventType)
                  "
                  @click="customEdit(item, index)"
                  >编辑</a-button
                >
                <a-button
                  style="margin-left: 4px"
                  type="primary"
                  v-if="['api', 'sdk'].includes(dataObj.basicData.appType)"
                  @click="$refs.nocodeOrApiTest.open(dataObj, item)"
                >
                  测试
                </a-button>
                <a-button
                  type="primary"
                  v-if="['chart'].includes(item.buttonEventAddDTO.eventType)"
                  @click="$refs.charConfigModal.open(index)"
                  >图表配置</a-button
                >
                <a-button
                  type="primary"
                  v-if="['report'].includes(item.buttonEventAddDTO.eventType)"
                  @click="handleReportConfig(index)"
                  >报表配置</a-button
                >
              </span>
            </template>
            <status-modal
              :button-data="dataObj.buttonData"
              :current="index"
            ></status-modal>

            <span
              v-if="
                ['add', 'edit'].includes(dataObj.mode) &&
                !(
                  labelNames.includes(item.buttonEventAddDTO.eventType) &&
                  index < 8
                )
              "
              class="dynamic-delete-button"
              @click="removeDomain(index)"
              >删除</span
            >
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <div v-if="['add', 'edit'].includes(dataObj.mode)">
            <a-button type="dashed" @click="addDomain" style="width: 100%">
              增加
            </a-button>
          </div>
        </a-col>
      </a-row>
    </a-form>
  </div>
</template>

<script>
import CustomBtnModal from "@/components/Form/base/customBtnModal.vue";
import debounce from "lodash/debounce";
import ChartConfigModal from "@/components/Form/base/chartConfigModal.vue";
import { clearNullValues } from "@/utils/util";
import _ from "lodash";
import StatusModal from "@/components/Form/base/StatusModal.vue";
import ReportConfigModal from "@/components/Form/base/reportConfigModal.vue";
import nocodeOrApiTest from "@/components/Form/nocodeOrApiTest.vue";

export default {
  name: "ButtonConfig",
  components: {
    ReportConfigModal,
    StatusModal,
    ChartConfigModal,
    CustomBtnModal,
    nocodeOrApiTest,
  },
  computed: {
    plugNameList() {
      return this.dataObj.pageData
        .concat(
          this.dataObj.defaultKeys,
          this.dataObj.exKeysData,
          this.plugExpression
        )
        .filter((item) => item.formData.dataIndex && item.formData.name)
        .map((item) => ({
          label: item.formData.anotherName || item.formData.name,
          value: item.formData.anotherName || item.formData.dataIndex,
          isExpression: !!item.isExpression,
        }));
    },
    nameList() {
      return this.dataObj.pageData
        .filter((item) => item.formData.dataIndex && item.formData.name)
        .map((item) => ({
          label: item.formData.name,
          value: item.formData.dataIndex,
        }));
    },
    allNameList() {
      const { pageData, defaultKeys, exKeysData } = this.dataObj;
      console.log(exKeysData, "33");
      return pageData
        .concat(defaultKeys, exKeysData)
        .filter((item) => item.formData.dataIndex && item.formData.name)
        .map((item) => ({
          label: item.formData.anotherName
            ? item.formData.subFormName + "_" + item.formData.anotherName
            : item.formData.name,
          value: item.formData.dataIndex,
        }));
    },
    isDisabled() {
      const arr = this.dataObj.buttonData
        .filter((ele) => ele.buttonEventAddDTO.foreignId)
        .map((ele) => ele.buttonEventAddDTO.foreignId);
      return arr;
    },
    buttonLength() {
      return this.dataObj.buttonLength;
    },
  },
  data() {
    return {
      labelCol: { span: 4 },
      wrapperCol: { span: 20 },
      form: {},
      labelNames: [
        "add",
        "query",
        "update",
        "del",
        "import",
        "export",
        "details",
        "batchDel",
      ],
      pluginfoList: [], // 所有插件列表
      plugExpression: [], // 插件表达式选项
      dataSourceList: [], // 数据源报表
      flowList: [], // 流程选项
      buttonIconList: [
        {
          value: "search",
          name: "search",
        },
        {
          value: "plus",
          name: "plus",
        },
        {
          value: "edit",
          name: "edit",
        },
        {
          value: "delete",
          name: "delete",
        },
        {
          value: "import",
          name: "import",
        },
        {
          value: "export",
          name: "export",
        },
        {
          value: "snippets",
          name: "snippets",
        },
        {
          value: "form",
          name: "form",
        },
        {
          value: "cloud-sync",
          name: "sync",
        },
        {
          value: "highlight",
          name: "highlight",
        },
        {
          value: "zoom-in",
          name: "zoom-in",
        },
        {
          value: "zoom-out",
          name: "zoom-out",
        },
        {
          value: "area-chart",
          name: "area-chart",
        },
        {
          value: "pie-chart",
          name: "pie-chart",
        },
        {
          value: "line-chart",
          name: "line-chart",
        },
      ],
      plugObj: {
        plugValue: "", // 插件ID
        plugName: "", // 插件名
        eventType: "", // 流程或插件
      },
    };
  },
  inject: ["dataObj"],
  methods: {
    handleTest() {
      // 测试
    },
    handleReportConfig(index) {
      const {
        buttonEventAddDTO: { foreignId },
      } = this.dataObj.buttonData[index];
      if (!foreignId) {
        this.$message.warning("请先选择数据源");
        return;
      }
      this.$refs.reportConfigModal.open(index);
    },
    // 查询数据源列表
    async queryDatasourceList(dataName) {
      try {
        // const result = await this.$http.post(
        //   `/datasource/querySourceAllList`,
        //   clearNullValues({
        //     dataTypeList: ["report"],
        //     dataName: dataName || "",
        //   })
        // );
        // const { data } = result;
        // this.dataSourceList = data;
      } catch (e) {
        console.error("请求失败", e);
      }
    },
    // 选择了
    changeFlowId(value, item) {
      item.serverInfoMap =
        this.flowList.find((e) => e.serviceItemId === value) || {};
    },
    // 下拉框按label搜索
    filterOption(input, option) {
      return (
        option.componentOptions.children[0].text
          .toLowerCase()
          .indexOf(input.toLowerCase()) >= 0
      );
    },
    onChangeDefaultFlag(value, item) {
      item.tableButtonAddDTO.defaultFlag = value === "0";
      if (!_.isArray(item.displayFields)) {
        this.$set(item, "displayFields", []);
      }
      if (value === "1") {
        item.displayFields = this.dataObj.pageData
          .filter((item) => item.isSendData && item.formData.type !== "editor")
          .map((item) => item.formData.dataIndex);
      }
    },
    // 无代码表单-任务还是插件
    noCodeSelectChange(e) {
      if (e === "api" || e === "sdk") {
        if (this.dataObj.buttonData.length === this.buttonLength) {
          this.dataObj.buttonData.push({
            checked: true,
            displayFields: [],
            buttonEventAddDTO: { eventType: "plug" },
            tableButtonAddDTO: {
              buttonName: "",
              buttonType: undefined,
              defaultFlag: false,
              buttonAfter: "flash",
              rendering: "1",
            },
            eventColumnMappingAddDTOList: [],
            columnPlugAddDTOList: [],
          });
        }
      } else {
        this.dataObj.buttonData.splice(this.dataObj.buttonData.length - 1, 1);
      }
    },
    // 自定义按钮
    async customChange(e, item) {
      delete item.columnNum;
      if (e === "chart") {
        item.tableButtonAddDTO.buttonType = "top";
      } else if (e === "update") {
        item.tableButtonAddDTO.buttonType = "data";
      } else if (e === "batchUp") {
        item.tableButtonAddDTO.buttonType = "top";
      } else if (e === "report") {
        item.tableButtonAddDTO.buttonType = "top";
      } else if (e === "details") {
        item.tableButtonAddDTO.buttonType = "data";
        item.columnNum = 1;
      } else if (e === "flow") {
        item.tableButtonAddDTO.buttonType = "top";
      } else if (e === "plug") {
        item.tableButtonAddDTO.buttonType = "top";
      }
      // this.$set(item.buttonEventAddDTO, 'foreignId', undefined)
      item.buttonEventAddDTO.foreignId = undefined;
    },
    // 查询插件表达式
    async queryPlugExpression() {
      try {
        const result = await this.$http.get("/foreignKey/queryPlugExpression");
        const { data } = result;
        console.log(data);
        this.plugExpression = Object.keys(data).map((key) => {
          return {
            isSendData: true,
            isExpression: true,
            formData: {
              name: key,
              dataIndex: data[key],
            },
          };
        });
      } catch (e) {
        console.error("请求失败", e);
      }
    },
    // 获取流程列表
    queryFlowList: debounce(async function (input) {
      try {
        const result = await this.$http.post(`/node/processModel/queryNoPage`, {
          title: input,
        });
        console.log(result);
        this.flowList = result.data;
      } catch (e) {
        console.error();
      }
    }, 600),
    // 插件列表
    async initPluginList() {
      const plugInfoListQueryDTO = {
        pageNo: 1,
        pageSize: 11110,
        plugEffectType: [],
        plugName: "",
        plugType: "exec",
      };
      // try {
      //   const result = await this.$http.post(`/pluginfo/list`, {
      //     plugInfoListQueryDTO,
      //   });
      //   if (result.code === 200) {
      //     this.pluginfoList = result.data;
      //   }
      // } catch (e) {
      //   console.error("操作失败", e);
      // } finally {
      // }
    },
    // 二级选项
    secondLevChange(value, item, index) {
      this.plugObj.plugValue = value;
    },
    async customEdit(item, index) {
      if (
        !item.tableButtonAddDTO.buttonName &&
        ["add", "edit"].includes(this.dataObj.mode)
      ) {
        return this.$message.warning("请先输入自定义按钮名");
      }
      if (item.buttonEventAddDTO.foreignId?.length === 0) {
        return this.$message.warning(
          item.buttonEventAddDTO.eventType === "flow"
            ? "请先选择流程"
            : "请先选择插件"
        );
      }
      try {
        if (item.buttonEventAddDTO.eventType === "flow") {
          // 流程
          const { foreignId: flowId } = item.buttonEventAddDTO;
          console.log("流程", flowId, this.flowList);
          const {
            modelId,
            version: modelVersion,
            modelName,
          } = this.flowList.find((e) => e.modelId === flowId) || {};
          const result = await this.$http.get(
            `/node/processModel/queryModelView`,
            {
              params: {
                modelId,
                modelVersion,
              },
            }
          );
          this.plugObj.plugName = modelName;
          this.plugObj.plugValue = flowId;
          this.plugObj.eventType = "flow";
          // 造一个格式算了
          const columnDefinition = result.data.columnDefinition;
          const inputParam = columnDefinition
            .split(",")
            .reduce((acc, key) => ({ ...acc, [key]: "" }), {});

          const data = [{ plugParamIODTO: { inputParam, outputParam: {} } }];
          this.$refs["customBtnModal"].open(data, item, index);
        } else {
          // 插件
          const result = await this.$http.post(`/pluginfo/queryByPlugIdList`, {
            plugIdList: [item.buttonEventAddDTO.foreignId],
          });
          const foundPlug = this.pluginfoList.find(
            (ele) => ele.plugId === item.buttonEventAddDTO.foreignId
          );
          if (foundPlug) {
            this.plugObj.plugName = foundPlug.plugName;
            this.plugObj.plugValue = foundPlug.plugId;
            this.plugObj.eventType = "plug";
          }
          this.$refs["customBtnModal"].open(result.data, item, index);
        }
      } catch (e) {
        console.error("操作失败", e);
      } finally {
      }
    },
    // 弹框保存
    async modalOk(modal) {
      console.info("参数", modal);
    },
    // 新增自定义按钮
    addDomain() {
      this.dataObj.buttonData.push({
        checked: true,
        hideButton: false,
        displayFields: [],
        disabledFields: [],
        chartConfig: {
          xField: undefined,
          yField: undefined,
          seriesField: undefined,
          gridsList: [],
        },
        dataSourceExpandAddDTOList: [],
        buttonEventAddDTO: { eventType: "plug", foreignId: undefined },
        tableButtonAddDTO: {
          buttonName: "",
          buttonType: undefined,
          defaultFlag: false,
          buttonAfter: "flash",
          rendering: "1",
        },
        eventColumnMappingAddDTOList: [],
        columnPlugAddDTOList: [],
      });
    },
    // 删除自定义按钮
    removeDomain(index) {
      this.dataObj.buttonData.splice(index, 1);
    },
  },
  created() {
    this.initPluginList();
    this.queryFlowList();
    this.queryPlugExpression();
    this.queryDatasourceList();
  },
};
</script>

<style lang="less" scoped>
.custom-select {
  width: 10%;
}
.custom-space {
  margin: 0 6px;
}

.custom-add-btn {
  margin-left: 35px;
}

.dynamic-delete-button {
  cursor: pointer;
  position: relative;
  top: 4px;
  font-size: 24px;
  color: #999;
  transition: all 0.3s;
  margin-left: 20px;
}

.dynamic-delete-button:hover {
  color: #777;
}

.dynamic-delete-button[disabled] {
  cursor: not-allowed;
  opacity: 0.5;
}
</style>
